package cn.sdormitory.controller.basedata;

import cn.sdormitory.basedata.dto.AssignClassDTO;
import cn.sdormitory.basedata.dto.AssignDormDTO;
import cn.sdormitory.basedata.dto.StudentExportDTO;
import cn.sdormitory.basedata.entity.BClass;
import cn.sdormitory.basedata.entity.BDormitory;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.basedata.service.BClassService;
import cn.sdormitory.basedata.service.BDormitoryService;
import cn.sdormitory.basedata.service.BStudentService;
import cn.sdormitory.basedata.vo.BStudentInfoVo;
import cn.sdormitory.common.annotation.IgnoreAuth;
import cn.sdormitory.common.annotation.SysLog;
import cn.sdormitory.common.api.CommonPage;
import cn.sdormitory.common.api.CommonResult;
import cn.sdormitory.common.api.UploadResult;
import cn.sdormitory.common.enums.BusinessType;
import cn.sdormitory.common.utils.StringUtils;
import cn.sdormitory.common.utils.poi.ExcelPoi;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.jsonwebtoken.lang.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.sdormitory.controller.test.FileUploadUtils;
import cn.sdormitory.controller.test.Result;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @创建人：zhouyang
 * @创建时间：2020/11/10 16:46
 * @version：V1.0
 */
@RestController
@Api(tags = "Basedata-bstudent=> 学员管理")
@RequestMapping("/basedata/bstudent")
@Slf4j
public class BStudentController {
    @Autowired
    private BStudentService bStudentService;
    @Autowired
    private BClassService bClassService;
    @Autowired
    private BDormitoryService bDormitoryService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Resource
    private FileUploadUtils fileUploadUtils;

    private String filePath = "/data/student/image";

    @ApiOperation("list => 根据条件分页获取学员列表")
    @PreAuthorize("@ss.hasPermi('basedata:bstudent:list')")
    @GetMapping(value = "/list")
    public CommonResult<CommonPage<BStudent>> list(@RequestParam Map<String, Object> params) {
        IPage<BStudent> page = bStudentService.getPage(params);
        return CommonResult.success(CommonPage.restPage(page));
    }

    @ApiOperation("{id} => 学员信息")
    @PreAuthorize("@ss.hasPermi('basedata:bstudent:query')")
    @GetMapping("/{id}")
    public CommonResult<BStudent> info(@PathVariable("id") Long id) throws Exception {
        return CommonResult.success(bStudentService.getBStudentById(id));
    }

    @IgnoreAuth
    @ApiOperation("{studentNo}=>学员信息")
    @GetMapping("/getStuByNo/{bstudentNo}")
    public CommonResult<BStudent> getStuByNo(@PathVariable("bstudentNo")String studentNo){
        return CommonResult.success(bStudentService.getByStudentNo(studentNo));
    }

    @ApiOperation("create => 新建学员信息")
    @PreAuthorize("@ss.hasPermi('basedata:bstudent:add')")
    @SysLog(title = "学员管理", businessType = BusinessType.INSERT)
    @PostMapping(value = "/create")
    public CommonResult<Integer> create(@RequestBody BStudent bStudent) throws IOException {
        BStudent bStudentInfo = bStudentService.getByStudentNo(bStudent.getStudentNo());
        if (bStudentInfo != null && !Objects.equals(bStudentInfo.getId(), bStudent.getId())) {
            return CommonResult.failed("该学号已存在");
        }

//        if (StrUtil.isBlank(bStudent.getPhone())) {
        bStudent.setStudentPassword(passwordEncoder.encode("123456"));
//        } else {
//            bStudent.setStudentPassword(passwordEncoder.encode(bStudent.getPhone()));
//        }

        int count = bStudentService.create(bStudent);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("update/{id} => 修改学员信息")
    @PreAuthorize("@ss.hasPermi('basedata:bstudent:edit')")
    @SysLog(title = "学员宿舍管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/update/{id}")
    public CommonResult<Integer> update(@PathVariable Long id, @RequestBody BStudent bStudent) {
        int count = bStudentService.update(id, bStudent);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("deleteByIds/{ids} => 删除指定学员信息")
    @PreAuthorize("@ss.hasPermi('basedata:bstudent:remove')")
    @SysLog(title = "学员管理", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/deleteByIds/{ids}")
    public CommonResult<Integer> deleteByIds(@PathVariable Long[] ids) {
//    public CommonResult<Integer> deleteByIds(@PathVariable String[] ids) {
        int count = bStudentService.deleteByIds(ids);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("update/status/{id} => 修改学员状态")
    @PreAuthorize("@ss.hasPermi('basedata:bstudent:edit')")
    @SysLog(title = "学员管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/update/status/{id}")
    public CommonResult<Integer> update(@PathVariable Long id, String status) {
        int count = bStudentService.updateStatus(id, status);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }
    
    @ApiOperation("/restore => 恢复学员信息")
    @PostMapping(value = "/restore")
    public CommonResult<Integer> restoreStudent(@RequestBody BStudent bStudent) {
        int count = bStudentService.restoreStudent(bStudent);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }
    
    //上传学员照片
//    @IgnoreAuth
    @PostMapping("/upload")
    public UploadResult upload(MultipartFile photo, HttpServletRequest request) throws IOException {
        InputStream inputStream=photo.getInputStream();
        byte[] iconData=new byte[(int)photo.getSize()];
        inputStream.read(iconData);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        UploadResult result = new UploadResult();

        //获取文件上传地址的真实路径
        String realPath =request.getSession().getServletContext().getRealPath("/uploadFile/");
        System.out.println("---------- "+request.getSession().getServletContext()
                .getRealPath("/"));
        String format = sdf.format(new Date());
        //构建文件对象
        File folder = new File(realPath+format);
        if(!folder.isDirectory()){ // 判断目录是否存在
            folder.mkdirs();  // 创建目录
        }
        // 获取上传文件的逻辑名称
        String oldName = photo.getOriginalFilename();
        // 给文件重命名，避免文件重名
        String newName = UUID.randomUUID().toString()+oldName
                .substring(oldName.lastIndexOf("."),oldName.length());
        try{
            // 上传文件至指定的目录
            photo.transferTo(new File(folder,newName));
            //获取文件上传后的完整地址
            String filePath = request.getScheme()+"://"+
                    request.getServerName()+":"+request.getServerPort()+""+request.getContextPath()+
                    "/uploadFile/"+format+newName;
            System.out.println("filePath:"+filePath);
            result.setSuccess(true);
            result.setMessage(filePath);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    // 录入人脸信息-学生
    @PostMapping("/addFaceInfo")
    @ApiOperation("录入人脸信息 => addFaceInfo")
    public CommonResult<Object> addFaceInfo(@RequestParam(value = "studentFaceInfo") String studentFaceInfoStr, @RequestParam(value = "faceImgPath") MultipartFile multipartFile) throws IOException {
        JSONArray jsonArray = JSON.parseArray(studentFaceInfoStr);
        BStudent student = JSONObject.toJavaObject((JSONObject) jsonArray.get(0), BStudent.class);
        log.info("studentFaceInfoStr:{}", studentFaceInfoStr);
        String photo = fileUploadUtils.uploadCompressorImageToTencentCos(multipartFile);
        Assert.notNull(photo,"上传人脸照片到腾讯云失败");
        student.setStuPhoto(photo);
        log.info("addFaceInfo param:{} photo:{}", student,photo);
        return bStudentService.addFaceInfo(student);
    }

    @PostMapping("/syncPhotoToAccessControl")
    @ApiOperation("同步人脸到门禁设备 => syncPhotoToAccessControl")
    public CommonResult<Object> syncPhotoToAccessControl(@RequestBody BStudent student) {
        // todo 须实现
        return CommonResult.failed("该功能还未实现，请实现");
    }

    @PostMapping("/syncPhotoToAttendance")
    @ApiOperation("同步人脸到考勤设备 => syncPhotoToAttendance")
    public CommonResult<Object> syncPhotoToAttendance(@RequestBody BStudent student) {
        // todo 须实现
        return CommonResult.failed("该功能还未实现，请实现");
    }

    /**
     * 文件上传（表单和文件同步上传）
     *
     * @returncreate
     */
    @PreAuthorize("@ss.hasPermi('basedata:bstudent:add')")
    @ApiOperation("createStu => 新建学生")
    @PostMapping(value = "/createStu")
    public CommonResult saveStu(@RequestParam(value = "upload") MultipartFile upload, BStudent bStudent) {
        if (upload.isEmpty()) {
            return CommonResult.failed("未上传照片");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        BStudent bStudentInfo = bStudentService.getByStudentNo(bStudent.getStudentNo());
        if (bStudentInfo != null && !Objects.equals(bStudentInfo.getId(), bStudent.getId())) {
            return CommonResult.failed("该学号已存在");
        }
        byte[] pictureData = null;
        // 使用输入流获取上传的图片
        InputStream inputStream = null;
        try {
            inputStream = upload.getInputStream();
            // 定义字节数组用于存放图片信息
            pictureData = new byte[(int) upload.getSize()];
            // 读取图片到字节数组中
            inputStream.read(pictureData);
        } catch (IOException e) {
            e.printStackTrace();
        }


        bStudent.setPhoto(pictureData);
        //根据班级ID查询班级名称
        BClass bClass = bClassService.getBClassById(bStudent.getClassId());
        bStudent.setClassName(bClass.getClassName());
        //根据宿舍ID查询宿舍号
//        BDormitory bDormitory=bDormitoryService.getBDormitoryById(Long.parseLong(bStudent.getBdormitoryId()));
        BDormitory bDormitory=bDormitoryService.getBDormitoryById(bStudent.getBdormitoryId());
        bStudent.setDormitoryNo(bDormitory.getDormitoryNo());

        int count = bStudentService.create(bStudent);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }


    /**
     * 根据id获取过闸人信息
     * @param id
     * @return
     */
    @ApiOperation("getPerson.do => 根据id获取过闸人信息")
    @GetMapping("/getPerson.do")
    public String getPerson(String id){
        return bStudentService.getPerson(id);
    }



    /**
     * 获取批量过闸人信息
     * @param number
     * @param offset
     * @return
     */
    @ApiOperation("listPersonByNumber.do => 获取批量过闸人信息")
    @GetMapping("/listPersonByNumber.do")
    public String listPersonByNumber(int number,int offset){
        return bStudentService.listPersonByNumber(number, offset);
    }

    /**
     * 根据id删除过闸人员信息
     * @param id
     * @return
     */
    @ApiOperation("removePerson.do => 根据id删除过闸人员信息")
    @GetMapping("/removePerson.do")
    public String removePerson(String [] id){
        return bStudentService.removePerson(id);
    }


    /**
     * 获取图片
     *
     * @param id
     * @param width
     * @param height
     * @param response
     * @throws IOException
     */
    @IgnoreAuth
    @ApiOperation("/getPhoto.do => 获取被修改者的照片")
    @GetMapping("/getPhoto.do")
    public void getPhotoById(Long id, int width, int height, final HttpServletResponse response) throws IOException {
        BStudent bStudentInfo = bStudentService.getBStudentById(id);
        byte[] data = bStudentInfo.getPhoto();
        if (width != 0 && height != 0) {
            data = scaleImage(data, width, height);
        }
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputSream = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            outputSream.write(buf, 0, len);
        }
        outputSream.close();
    }

    @ApiOperation("updateAndUpload/ => 修改学员信息(包含文件上传)")
    @PreAuthorize("@ss.hasPermi('basedata:bstudent:edit')")
    @PostMapping (value = "/updateAndUpload")
    public CommonResult<Integer> updateAndUpload(BStudent bStudent, @RequestParam(value = "upload") MultipartFile upload) {

        //根据班级ID查询班级名称
        BClass bClass = bClassService.getBClassById(bStudent.getClassId());
        bStudent.setClassName(bClass.getClassName());
        //根据宿舍ID查询宿舍号
//        BDormitory bDormitory=bDormitoryService.getBDormitoryById(Long.parseLong(bStudent.getBdormitoryId()));
        System.out.println("BdormitoryId-----------  "+bStudent.getBdormitoryId());
        BDormitory bDormitory=bDormitoryService.getBDormitoryById(bStudent.getBdormitoryId());
        System.out.println("DormitoryNo-----------  "+bDormitory.getDormitoryNo());
        bStudent.setDormitoryNo(bDormitory.getDormitoryNo());

        if (upload.isEmpty()) {
            System.out.println("...... 文件上传对象为null。。。。。。。。。");
            int count = bStudentService.update(bStudent.getId(), bStudent);
        } else {
            System.out.println(" 修改学生信息选择了文件 ..........");
            byte[] pictureData = null;
            // 使用输入流获取上传的图片
            InputStream inputStream = null;
            try {
                inputStream = upload.getInputStream();
                // 定义字节数组用于存放图片信息
                pictureData = new byte[(int) upload.getSize()];
                // 读取图片到字节数组中
                inputStream.read(pictureData);
                bStudent.setPhoto(pictureData);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int count = bStudentService.update(bStudent.getId(), bStudent);
            if (count > 0) {
                return CommonResult.success(count);
            }
        }
        return CommonResult.failed();
    }


    /**
     * 显示图片
     *
     * @param data   byet流
     * @param width  图片的宽度
     * @param height 图片的高度
     * @return 2020.11.19
     * @throws IOException
     */
    public static byte[] scaleImage(byte[] data, int width, int height) throws IOException {
        BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));
        int imageOldWidth = buffered_oldImage.getWidth();
        int imageOldHeight = buffered_oldImage.getHeight();
        double scale_x = (double) width / imageOldWidth;
        double scale_y = (double) height / imageOldHeight;
        double scale_xy = Math.min(scale_x, scale_y);
        int imageNewWidth = (int) (imageOldWidth * scale_xy);
        int imageNewHeight = (int) (imageOldHeight * scale_xy);
        BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);
        buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);
        buffered_newImage.getGraphics().dispose();
        ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();
        ImageIO.write(buffered_newImage, "jpeg", outPutStream);
        return outPutStream.toByteArray();
    }

    @ApiOperation("importTemplate => 下载模板")
    @SysLog(title = "学员管理", businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        EasyExcel.write(response.getOutputStream(), BStudent.class).sheet("学员管理").doWrite(null);
    }

    @IgnoreAuth
    @ApiOperation("importData => 导入学员信息")
    @SysLog(title = "学员管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public CommonResult importData(@RequestParam(value = "upload") MultipartFile upload) throws Exception
    {
        try{
            if(upload == null || upload.getSize() == 0){
                return CommonResult.failed("文件为空!!!");
            }
            List<BStudent> list = new ExcelPoi<BStudent>().importObjectList(upload.getInputStream(), upload.getOriginalFilename(), BStudent.class);
            Iterator<BStudent> iterator = list.iterator();
            while (iterator.hasNext())
            {
                BStudent bStudent = iterator.next();
                int num = bStudentService.insert(bStudent);
                if(num == -10){
                    return CommonResult.failed("姓名不能为空!!!");
                }
                if(num == -11){
                    return CommonResult.failed("班级不能为空!!!");
                }
                if(num == -12){
                    return CommonResult.failed("学号不能为空!!!");
                }
                if(num == -13){
                    return CommonResult.failed("手机号不能为空!!!");
                }
                if(num == -1){
                    return CommonResult.failed("导入的学员信息: "+bStudent.getStudentNo()+" 对应的班级不存在，请先添加班级!!!");
                }
                if(num == -2){
                    return CommonResult.failed("导入的学员信息: "+bStudent.getStudentNo()+" 对应的性别有误!!!");
                }
                if(num == -3){
                    return CommonResult.failed("导入的学员信息: "+bStudent.getStudentNo()+" 对应的栋号不存在，请先添加栋号!!!");
                }
                if(num == -4){
                    return CommonResult.failed("导入的学员信息: "+bStudent.getStudentNo()+" 对应的楼层不存在，请先添加楼层!!!");
                }
                if(num == -5){
                    return CommonResult.failed("导入的学员信息: "+bStudent.getStudentNo()+" 栋号+楼层+宿舍号对应的宿舍信息不匹配!!!");
                }
                if(num == -6){
                    return CommonResult.failed("导入的学员信息："+bStudent.getStudentNo()+" 学号重复!!!");
                }

            }
        } catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("学员信息导入失败!!!");
        }
        return CommonResult.success("学员信息导入成功!!!");
    }

    @ApiOperation("listAll => 根据班级查询对应的寄宿学员列表")
    @GetMapping(value = "/getStuInfoByClassId/{classId}")
    public CommonResult<List<BStudentInfoVo>> getStuInfoByClassId(@PathVariable("classId")Long classId) {
        List<BStudentInfoVo> bStudentInfoVoList = bStudentService.getStuInfoByClassId(classId);
        return CommonResult.success(bStudentInfoVoList);
    }

    @IgnoreAuth
    @ApiOperation("importData1 => 导入在读学员信息")
    @SysLog(title = "学员管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData1")
    public CommonResult importData1(@RequestParam(value = "upload") MultipartFile upload) throws Exception
    {
        try{
            if(upload == null || upload.getSize() == 0){
                return CommonResult.failed("文件为空!!!");
            }
            List<BStudent> list = new ExcelPoi<BStudent>().importObjectList(upload.getInputStream(), upload.getOriginalFilename(), BStudent.class);
            Iterator<BStudent> iterator = list.iterator();
            while (iterator.hasNext())
            {
                BStudent bStudent = iterator.next();
                int num = bStudentService.insert1(bStudent);
                if(num == -10){
                    return CommonResult.failed("姓名不能为空!!!");
                }
                if(num == -11){
                    return CommonResult.failed("班级不能为空!!!");
                }
                if(num == -12){
                    return CommonResult.failed("学号不能为空!!!");
                }
                if(num == -13){
                    return CommonResult.failed("手机号不能为空!!!");
                }
                if(num == -1){
                    return CommonResult.failed("导入的学员信息: "+bStudent.getStudentNo()+" 对应的班级不存在，请先添加班级!!!");
                }
                if(num == -2){
                    return CommonResult.failed("导入的学员信息: "+bStudent.getStudentNo()+" 对应的性别有误!!!");
                }

                if(num == -6){
                    return CommonResult.failed("导入的学员信息："+bStudent.getStudentNo()+" 学号重复!!!");
                }

            }
        } catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("学员信息导入失败!!!");
        }
        return CommonResult.success("学员信息导入成功!!!");
    }

    @PutMapping("/assign/class")
    public CommonResult assignClass(@RequestBody AssignClassDTO dto){
        return bStudentService.assignClass(dto);
    }

    @PutMapping("/assign/dorm")
    public CommonResult assignDorm(@RequestBody AssignDormDTO dto){
        return bStudentService.assignDorm(dto);
    }


    @IgnoreAuth
    @ApiOperation("importUpdate => 更新导入")
    @SysLog(title = "学员管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importUpdate")
    public CommonResult importUpdate(@RequestParam(value = "upload") MultipartFile upload) throws Exception
    {
        try{
            if(upload == null || upload.getSize() == 0){
                return CommonResult.failed("文件为空!!!");
            }
            List<BStudent> list = new ExcelPoi<BStudent>().importObjectList(upload.getInputStream(), upload.getOriginalFilename(), BStudent.class);
            Iterator<BStudent> iterator = list.iterator();
            while (iterator.hasNext())
            {
                //excel中学生数据
                BStudent excelStudent = iterator.next();
                //数据库中学生数据
                BStudent dbStudent = bStudentService.getByStudentNo(excelStudent.getStudentNo());

                if(StringUtils.isEmpty(dbStudent.getParentName()) || StringUtils.isEmpty(dbStudent.getParentPhone())){
                    if(StringUtils.isEmpty(excelStudent.getParentPhone()) &&
                            StringUtils.isEmpty(excelStudent.getParentName())){
                        continue;
                    }
                    if(!StringUtils.isEmpty(excelStudent.getParentName())){
                        dbStudent.setParentName(excelStudent.getParentName());
                    }
                    if(!StringUtils.isEmpty(excelStudent.getParentPhone())){
                        dbStudent.setParentPhone(excelStudent.getParentPhone());
                    }
                    bStudentService.update(dbStudent.getId(),dbStudent);
                }else {
                    continue;
                }
//                Class stuClazz = BStudent.class;
//                Field[] fields = stuClazz.getDeclaredFields();
//                for(Field field:fields){
//                    String fieldName = field.getName();
//                    String firstCharUpper = fieldName.substring(0, 1).toUpperCase();
//                    String invokeMethodName = "get" + firstCharUpper + fieldName.substring(1);
//                }
            }
        } catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("学员信息更新失败!!!");
        }
        return CommonResult.success("学员信息更新成功!!!");
    }

    @GetMapping("/export")
    public CommonResult exportStu(HttpServletResponse response, @RequestParam Map<String, Object> params){
        List<BStudent> exportList = bStudentService.getStuList(params);
        try {
            EasyExcel.write(response.getOutputStream(), BStudent.class).sheet("学生名单").doWrite(exportList);
            return CommonResult.success();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.failed();
    }

    /**
     * 导出一个excel表 包含 学生ID，手机号，姓名，班级，楼栋，楼层，宿舍号,按楼栋 楼层 宿舍号排序
     * @param response
     * @return
     */
    @GetMapping("/export2")
    public CommonResult export2(HttpServletResponse response){
        List<StudentExportDTO> exportList = bStudentService.getStuListOrderByDor();
        try {
            EasyExcel.write(response.getOutputStream(), StudentExportDTO.class).sheet("学生名单").doWrite(exportList);
            return CommonResult.success();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.failed();
    }

    @ApiOperation("上传学生照片")
    @PostMapping("/uploadImage")
    public Result<String> uploadImage(MultipartFile file) throws IOException {
        return fileUploadUtils.upload(file, filePath);
    }

    @ApiOperation("根据ID查询学生信息")
    @GetMapping("/getStudentById/{id}")
    public CommonResult getStudentById(@PathVariable("id")String id) {
        return CommonResult.success(bStudentService.getStudentById(id));
    }

    @ApiOperation("重置密码")
    @PutMapping("/resetPwd/{ids}")
    public CommonResult resetPwd(@PathVariable Long[] ids){
        int count = bStudentService.resetPwd(ids);
        if (count == 0) {
            return CommonResult.success("当前选中学生密码全部重置成功");
        }else if(count == 1){
            return CommonResult.success("当前选中学生密码部分重置成功");
        }else {
            return CommonResult.failed();
        }
    }

//    @ApiOperation("分配宿舍和床位")
//    @RequestMapping(method = RequestMethod.POST,value = "/allocateDormitoryAndBed")
//    public CommonResult allocateDormitoryAndBed(@RequestBody Map<String,Long> map){
//        boolean flag = bStudentService.allocateDormitoryAndBed(map);
//        if (flag) {
//            return CommonResult.success();
//        }
//        return CommonResult.failed();
//    }

}
